﻿@using RadzenBlazorDemos.Data
@using RadzenBlazorDemos.Models.Northwind
@using Microsoft.EntityFrameworkCore

@inherits DbContextPage

<RadzenDataGrid @ref="grid" AllowFiltering="true" AllowSorting="true" AllowColumnResize="true"
                Data="@employees" TItem="Employee" RowRender="@RowRender" LoadChildData="@LoadChildData" 
                RowCollapse="@(args => grid.ColumnsCollection.ToList().ForEach(c => c.ClearFilters()))">
    <Columns>
        <RadzenDataGridColumn TItem="Employee" Title="Employee" Frozen="true" Sortable="false" Filterable="false" Width="300px">
            <Template Context="data">
                <RadzenImage Path="@data.Photo" class="rz-gravatar me-1" />
                <strong>@data.TitleOfCourtesy @data.FirstName @data.LastName</strong>
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="Employee" Property="Title" Title="Job Title" Width="240px" />
        <RadzenDataGridColumn TItem="Employee" Property="HireDate" Title="Hire Date" FormatString="{0:d}" Width="160px" />
        <RadzenDataGridColumn TItem="Employee" Property="City" Title="City" Width="200px" />
        <RadzenDataGridColumn TItem="Employee" Property="HomePhone" Title="Home Phone" Width="200px" />
        <RadzenDataGridColumn TItem="Employee" Property="Extension" Title="Extension" />
    </Columns>
</RadzenDataGrid>

@code {
    IEnumerable<Employee> employees;
    RadzenDataGrid<Employee> grid;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        employees = dbContext.Employees.Where(e => e.ReportsTo == null);
    }

    void RowRender(RowRenderEventArgs<Employee> args)
    {
        args.Expandable = dbContext.Employees.Where(e => e.ReportsTo == args.Data.EmployeeID).Any();
    }

    void LoadChildData(DataGridLoadChildDataEventArgs<Employee> args)
    {
        args.Data = dbContext.Employees.Where(e => e.ReportsTo == args.Item.EmployeeID);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        base.OnAfterRender(firstRender);

        if (firstRender)
        {
            await grid.ExpandRow(employees.FirstOrDefault());
        }
    }
}